package com.arpa.ntocc.basic.api.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.arpa.ntocc.basic.api.domain.dto.AppInfoDTO;
import com.arpa.ntocc.basic.api.domain.entity.AppInfo;
import com.arpa.ntocc.basic.api.domain.vo.AppInfoVO;
import com.arpa.ntocc.basic.api.mapper.AppInfoMapper;
import com.arpa.ntocc.basic.api.service.IAppInfoService;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.CommonUtil;
import com.arpa.ntocc.common.common.util.OBSUtil;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * <p>
 * APP发布信息 服务实现类
 * </p>
 *
 * @author LEO
 * @since 2020-03-17
 */
@Service
public class AppInfoServiceImpl extends ServiceImpl<AppInfoMapper, AppInfo> implements IAppInfoService {

    /**
     * 保存
     *
     * @param appInfo
     * @return
     */
    @Override
    public boolean save(AppInfo appInfo) {
        try {
            byte[] qrBytes = QrCodeUtil.generatePng(appInfo.getLink(), 400, 400);
            String qrTempPath = System.getProperty("user.home") + "/NTOCC_APP_QRCODE/" + IdUtil.fastSimpleUUID() + ".png";
            File qrTemp = FileUtil.writeBytes(qrBytes, qrTempPath);
            String qrlink = OBSUtil.uploadFile(qrTemp);
            appInfo.setQrCode(qrlink);
            if (appInfo.getId()!=null) {
                appInfo.setCreatedBy(UserUtil.getCode());
                return super.save(appInfo);
            } else {
                appInfo.setModifiedBy(UserUtil.getCode());
                return super.updateById(appInfo);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ServiceException("上传APK文件失败！");
        }

    }

    /**
     * 查询列表
     *
     * @param appInfoDTO
     * @return
     */
    @Override
    public List<AppInfoVO> queryList(AppInfoDTO appInfoDTO) {
        //排序字段名需要驼峰转数据库下划线类型字段名
        if (StringUtils.isNotEmpty(appInfoDTO.getSortField())) {
            appInfoDTO.setSortField(CommonUtil.camel2Underline(appInfoDTO.getSortField()));
        }
        List<AppInfoVO> appInfoVOList = baseMapper.queryList(appInfoDTO);
        return appInfoVOList;
    }

    /**
     * 查询合计,包含总数
     *
     * @param appInfoDTO
     * @return
     */
    @Override
    public AppInfoVO queryListSum(AppInfoDTO appInfoDTO) {
        AppInfoVO appInfoVO = baseMapper.queryListSum(appInfoDTO);
        return appInfoVO;
    }

}
